package cn.shadow.clienthandler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;


public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    /**
     * 通道就绪，就会触发该方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("通道就绪");
        //向服务端发送消息，发送心跳信息
        ByteBuf byteBuf = BufferUtil.onlySendHeaderMessage(1, 3);
        BufferUtil.writeUTF(byteBuf, "100-1-a937375155");
        ctx.writeAndFlush(byteBuf);
        System.out.println("发送完毕");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            switch (event.state()) {
                case READER_IDLE:
                    System.out.println("读空闲");
                    break;
                case ALL_IDLE:
                    System.out.println("读写空闲");
                    break;
                case WRITER_IDLE:
                    System.out.println("写空闲");
                    break;
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("re" + msg);
    }
}
